package com.dd.keel.core.common.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dd.keel.core.common.ini.IniReader;


public class EtcConfig {
	
	final static private Logger LOGGER = LoggerFactory.getLogger(EtcConfig.class);
	
	private static String ETC_CONFIG_FILE = "server.ini";
	private static IniReader iniReader = null;
	private static Object server_ini_lock = new Object();
	private static String keel_home = null;
	
	
	public static String getCommonConfigValue(String key)
	{
		return getConfigValue("common",key);
	}
	
	/**
	 * Set 'keel.home' env
	 * @param keelHomeRealPath
	 */
	public static void setKeelHomePath(String keelHomeRealPath)
	{
		if(keelHomeRealPath!=null)
		{
			keelHomeRealPath = keelHomeRealPath.trim();
			keelHomeRealPath = keelHomeRealPath.replace('\\', '/');
			File dirFile = new File(keelHomeRealPath);
			if(dirFile.exists())
			{
				keel_home = keelHomeRealPath;
				if(keel_home.endsWith("/"))
				{
					keel_home = keel_home.substring(0,keel_home.length()-1);
				}
				keel_home = keel_home.replaceFirst("file:/", "");
				LOGGER.info("jvm env 'keel.home' is set [{}]", keel_home );
			}
		}
	}
	
	public static String getKeelHomePath()
	{
		if(keel_home==null)
		{
			keel_home = System.getProperty("keel.home");
			if(keel_home==null)
			{
				keel_home = ".";
			}
			keel_home = keel_home.trim();
			if(keel_home.endsWith("/"))
			{
				keel_home = keel_home.substring(0,keel_home.length()-1);
			}
			keel_home = keel_home.replaceFirst("file:/", "");
			LOGGER.info("jvm env 'keel.home' is set [{}]", keel_home );
		}
		return keel_home;
	}
	
	public static String filter(String value)
	{
		if(value==null) return "";
		value = value.trim();
		int index = value.indexOf("${keel.home}");
		if(index>0)
		{
			value = value.substring(0,index) + getKeelHomePath() + value.substring(index+"${keel.home}".length());
		}
		else if(index==0)
		{
			value = getKeelHomePath() + value.substring("${keel.home}".length());
		}
		value = value.trim();
		return value;
	}
	
	private static void checkIniReader() {
		if(iniReader==null){
			synchronized(server_ini_lock)
			{
				if(iniReader==null){
					String config_file_name = FileUtil.retrieveConfigFilepath(ETC_CONFIG_FILE);
					File confi_file = new File(config_file_name);
					if(confi_file.exists())
					{
						try {
							iniReader = new IniReader(confi_file);
						} catch (Exception e) {
							LOGGER.error(e.getMessage(), e);
						}
					}
				}
			}
		}
	}
	
	/**
	 * Get Config General Keys
	 * like : [datasources/obs_db],[datasources/mem_db]
	 * Call getConfigGeneralKey("datasources") then return [obs_db,mem_db]
	 * @param sectionName
	 * @return
	 */
	public static String[] getConfigSectionNameWithStart(String sectionName) {
		checkIniReader();
		if(iniReader!=null)
		{
			List<String> ls = new ArrayList<String>();
			Iterator<String> it = iniReader.getAllSectionNames();
			while (it.hasNext()) {
				String s = it.next();
				if (s != null && s.startsWith(sectionName)) {
					ls.add(s);
				}
			}
			return ls.toArray(new String[0]);
		}
		else
		{
			return new String[0];
		}
	}
	
	public static String getConfigValue(String sectionName,String key)
	{
		checkIniReader();
		if(iniReader!=null)
		{
			Properties props = iniReader.getSectionProps(sectionName);
			String value = props.getProperty(key);
			value = filter(value);
			return value;
		}
		else
		{
			return "";
		}
	}
	
	public static long getLongConfigValue(String sectionName,String key)
	{
		String value = getConfigValue(sectionName,key);
		return StringUtil.getLongValue(value);
	}
	
	public static int getIntConfigValue(String sectionName,String key)
	{
		String value = getConfigValue(sectionName,key);
		return (int)StringUtil.getLongValue(value);
	}
	
	public static boolean getBooleanConfigValue(String sectionName,String key)
	{
		String value = getConfigValue(sectionName,key);
		if(value!=null && value.equalsIgnoreCase("true"))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
}
